package com.huhao.springbootremotecallbyrabbitmq.service;

import com.huhao.springbootremotecallbyrabbitmq.constants.RabbitMqConstants;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.amqp.core.Message;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author huhao
 */
@Component
public class MessageConsumer {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(
            bindings = @QueueBinding(
                    exchange = @Exchange(value = RabbitMqConstants.EXCHANGE_NAME),
                    key = RabbitMqConstants.ROUTING_KEY,
                    value = @Queue(value = RabbitMqConstants.QUEUE_NAME, durable = "true")
            )
    )
    public void handleRpcRequest(Message message, @Header(AmqpHeaders.REPLY_TO) String replyTo, @Header(AmqpHeaders.CORRELATION_ID) String correlationId) {
        // 从消息中提取请求数据
        String requestData = new String(message.getBody(), StandardCharsets.UTF_8);
        System.err.println("message: " + requestData);
        // 处理请求并生成响应
        String responseData = "Processed: " + requestData;
        // 将响应发送到回复队列
        MessageProperties responseProperties = new MessageProperties();
        responseProperties.setReplyTo(replyTo);
        // 保持correlationId以便客户端能够匹配请求和响应
        responseProperties.setCorrelationId(correlationId);
        Message responseMessage = new Message(responseData.getBytes(StandardCharsets.UTF_8), responseProperties);
        // 使用RabbitTemplate发送响应消息到回复队列
        rabbitTemplate.convertAndSend(replyTo, responseMessage);
    }
}
